const Router = require("koa-router")
const ResBody = require("../struct/ResBody")
const Sequelize = require('sequelize');

const { Customer, Cate, Goods, GoodsAttrConfig, GoodsAttrValue, GoodsAttr, Building, User, Room, Floor } = require("../model")

const { CustomerController } = require("../controller")
const router = new Router()
const utils = require("../utils/index.js")

// 列表
router.get("/index", async ctx => {
  const store_id = ctx.header.storeid;
  const { customer_name } = ctx.request.query
  const { rows, count } = await Customer.findAndCountAll({ where: { store_id } });

  const orderGoods = await CustomerController.customerIndex({ store_id });
  // console.log('Customer--index--res==%s==', JSON.stringify(res));
  console.log('Customer--index--orderGoods==%s==', JSON.stringify(orderGoods));
  let list = rows.map(d => {
    const item = JSON.parse(JSON.stringify(d));
    item.skuOrder = [];
    if (orderGoods.length) {
      item.skuOrder = orderGoods.filter(o => o.customer_id === d.id);
    };
    return item
  })

  ctx.body = new ResBody({ data: { list, count } })
})
// 商品详情
router.get("/detail", async ctx => {
  // console.log('goods_index--%s===', JSON.stringify(ctx));
  const store_id = ctx.header.storeid;
  const { id } = ctx.request.query
  utils.checkParams({ id })

  const result = await Customer.findByPk(id);
  console.log('Customer--detail==%s==', JSON.stringify(result));
  if (!result) {
    return ctx.body = new ResBody({ data: '未找到该客户信息', code: 500, msg: '未找到该客户信息' })
  }
  ctx.body = new ResBody({ data: result })
})
// 添加；
router.post("/add", async ctx => {
  const { role } = ctx.state.user
  const store_id = ctx.header.storeid;
  if (role !== "superAdmin") {
    // throw new Error("403-拒绝访问API")
    return ctx.body = new ResBody({ success: false, code: 403, msg: '拒绝访问API' })
  }
  const {
    company_name,
    full_company_name,
    customer_name,
    phone,
    tel_phone,
    area,
    area_address,
    company_type,
    customer_type,
    bank_name,
    bank,
    status = 1,
    remarks,
    is_delete = 0,
  } = ctx.request.body
  utils.checkParams({ company_name, full_company_name, customer_name, phone, area, area_address, company_type, customer_type })
  try {
    const data = await Customer.create({
      store_id,
      company_name,
      full_company_name,
      customer_name,
      phone,
      tel_phone,
      area,
      area_address,
      company_type,
      customer_type,
      bank_name,
      bank,
      status,
      remarks,
      is_delete
    })
    console.log('Customer--add--data:%s==', typeof (data), JSON.stringify(data));
    return ctx.body = new ResBody({ data })
  }
  catch (err) {
    console.log('Customer--add--err:%s==', JSON.stringify(err));
    const errorData = utils.errorBody(err)
    console.log('Customer--add--errorData:%s==', JSON.stringify(errorData));
    return ctx.body = new ResBody({ data: errorData })
    // return ctx.body = new ResBody({ data: { code: 0, msg: '失败' } })
  }
  // const goods = await Goods.findOrCreate({ where: { goods_name, full_goods_name, store_id }, defaults: { goods_name, full_goods_name, cat_id, attr, stock, sales, unit_name, unit_name2, unit_convert, unit_convert2, weight, desc, sort, store_id, is_hot, is_recommend, status, is_delete, slider_image, content } })
  console.log('Customer--add--data:%s==', typeof (data), JSON.stringify(data));
  ctx.body = new ResBody({ data })
})

// 添加商品；
router.post("/update", async ctx => {
  const { role } = ctx.state.user
  const store_id = ctx.header.storeid;
  console.log('store_id==%s==', store_id);
  if (role !== "superAdmin") {
    // throw new Error("403-拒绝访问API")
    return ctx.body = new ResBody({ success: false, code: 403, msg: '拒绝访问API' })
  }
  const { id, company_name, customer_type, area } = ctx.request.body;
  const params = ctx.request.body;
  utils.checkParams({ id, company_name, customer_type, area });
  delete params.update_time;
  const result = await Customer.update(params, { where: { id } })
  // const goods = await Goods.findOrCreate({ where: { goods_name, full_goods_name, store_id }, defaults: { goods_name, full_goods_name, cat_id, attr, stock, sales, unit_name, unit_name2, unit_convert, unit_convert2, weight, desc, sort, store_id, is_hot, is_recommend, status, is_delete, slider_image, content } })
  console.log('Customer--update--result: %s==', JSON.stringify(result));
  ctx.body = new ResBody({ data: result })
})

// 修改商品规格 
router.post("/updateAttrValue", async ctx => {
  const store_id = ctx.header.storeid;
  const { role } = ctx.state.user
  if (role !== "superAdmin") {
    // throw new Error("403-拒绝访问API")
    return ctx.body = new ResBody({ success: false, code: 403, msg: '拒绝访问API' })
  }
  const { id, attr_list } = ctx.request.body
  const attrResult = CustomerController.bulkCreateGoodsAttr({ ...ctx.request.body }, id, store_id)
  console.log('attrResult--%s==', attrResult);

  ctx.body = new ResBody({ data: '', code: 200, msg: '操作成功' })
})

// 修改商品规格(废弃)
router.post("/updateAttrValue2", async ctx => {
  const store_id = ctx.header.storeid;
  const { role } = ctx.state.user
  if (role !== "superAdmin") {
    // throw new Error("403-拒绝访问API")
    return ctx.body = new ResBody({ success: false, code: 403, msg: '拒绝访问API' })
  }
  const { goods_id, attr_list } = ctx.request.body
  const list = attr_list.map(d => {
    d.goods_id = goods_id;
    return d;
  })
  console.log('updateAttrValue--goods_id: %s--attr_list: %s==', goods_id, JSON.stringify(list));
  GoodsAttrValue.bulkCreate(list, { updateOnDuplicate: ["price", "retail_price", "cost_price", "stock", "weight", "code", "sort"] })
    .then(res => {
      console.log('updateAttrValue--res: %s==', JSON.stringify(res));
    })
    .catch(err => {
      console.log('updateAttrValue--err: %s==', JSON.stringify(err));
    })

  ctx.body = new ResBody({ data: '', code: 200, msg: '操作成功' })
  return;

  utils.checkParams({ goods_id })

  const findData = await GoodsAttrConfig.findOrCreate({ where: { goods_id, store_id }, defaults: { goods_id, store_id, config } })
  console.log('findData--%s==', JSON.stringify(findData));
  if (!findData[1]) {
    const res = await GoodsAttrConfig.update(
      { config }, {
      where: { goods_id, store_id }
    })
    console.log('GoodsAttrConfig.update--res--%s==', res);
    return ctx.body = new ResBody({ data: res, code: 200, msg: '操作成功' })
  }
  ctx.body = new ResBody({ data: findData, code: 200, msg: '操作成功' })
})

// 添加商品规格配置 attr_config；
router.post("/updateAttrConfig", async ctx => {
  const store_id = ctx.header.storeid;
  const { role } = ctx.state.user
  if (role !== "superAdmin") {
    // throw new Error("403-拒绝访问API")
    return ctx.body = new ResBody({ success: false, code: 403, msg: '拒绝访问API' })
  }
  const { id: goods_id, attr_list } = ctx.request.body
  utils.checkParams({ goods_id })

  const findData = await GoodsAttrConfig.findOrCreate({ where: { goods_id }, defaults: { goods_id, config: JSON.stringify(attr_list) } })
  console.log('findData--%s==', JSON.stringify(findData));
  if (!findData[1]) {
    const res = await GoodsAttrConfig.update(
      { config: JSON.stringify(attr_list) },
      {
        where: { goods_id }
      })
    console.log('GoodsAttrConfig.update--res--%s==', res);
    return ctx.body = new ResBody({ data: res, code: 200, msg: '操作成功' })
  }
  // if (findData) {
  //   // throw new Error(`${goods_name}-${full_goods_name} 商品已存在`)
  //   return ctx.body = new ResBody({ success: false, msg: '该商品已存在' })
  // }
  // const goods = await Goods.createCate({ goods_name, full_goods_name, cat_id, attr, stock, sales, weight, desc, ord, store_id, is_hot, is_recommend, status, is_delete, slider_image, content })
  ctx.body = new ResBody({ data: findData, code: 200, msg: '操作成功' })
})


// 添加商品规格；
router.post("/addAttr", async ctx => {
  console.log('addAttr--%s--%s==', JSON.stringify(ctx), JSON.stringify(ctx.state.user));
  const { role } = ctx.state.user
  if (role !== "superAdmin") {
    // throw new Error("403-拒绝访问API")
    return ctx.body = new ResBody({ success: false, code: 403, msg: '拒绝访问API' })
  }
  const { goods_id, store_id, attr_name, attr_values, status, is_delete = 0 } = ctx.query
  utils.checkParams({ goods_id, store_id, attr_name, attr_values })

  const findGoods = await Goods.findOne({ where: { goods_name, full_goods_name, store_id } })
  console.log('findGoods--%s==', findGoods);
  if (findGoods) {
    // throw new Error(`${goods_name}-${full_goods_name} 商品已存在`)
    return ctx.body = new ResBody({ success: false, msg: '该商品已存在' })
  }
  const goods = await Goods.createCate({ goods_name, full_goods_name, cat_id, attr, stock, sales, weight, desc, ord, store_id, is_hot, is_recommend, status, is_delete, slider_image, content })
  ctx.body = new ResBody({ data: goods })
})




router.get("/getManageBuildings", async ctx => {
  const { role, userId } = ctx.state.user
  const user = await User.findById(userId)
  let buildings = []
  switch (user.role) {
    case "superAdmin":
      buildings = await Building.findAll()
      break
    case "admin":
      buildings = await user.getBuildings()
      break
    default:
      buildings = []
      break
  }
  ctx.body = new ResBody({ data: { buildings, role } })
})

router.get("/getBuildingInfo", async ctx => {
  const { buildingId } = ctx.request.query
  const building = await Building.findOne({ where: { id: buildingId } })
  const result = building.toJSON()
  result.floorCount = await Floor.count({ where: { buildingId } })
  result.roomCount = await Room.count({ where: { buildingId } })
  result.studentCount = (
    await BuildingController.getStudents(buildingId)
  ).length
  ctx.body = new ResBody({ data: result })
})

router.post("/addBuildingWithRoom", async ctx => {
  const { role } = ctx.state.user
  if (role !== "superAdmin") {
    throw new Error("403-拒绝访问API")
  }
  const { name, floorCount, roomCount } = ctx.request.body
  utils.checkParams({ name, floorCount, roomCount })
  const building = await Building.createBuilding({ name })
  // 为宿舍楼添加楼层
  for (let i = 1; i <= floorCount; i++) {
    const floor = await Floor.createFloor({ layer: i, buildingId: building.id })
    await Building.addFloor(building.id, floor)
    // 为楼层添加房间
    for (let j = 1; j <= roomCount; j++) {
      await Room.createRoom({
        number: i * 100 + j,
        floorId: floor.id,
        buildingId: building.id
      })
    }
  }
  ctx.body = new ResBody({ data: building })
})

router.del("/delBuilding", async ctx => {
  const { role } = ctx.state.user
  if (role !== "superAdmin") {
    throw new Error("403-拒绝访问API")
  }
  const { id } = ctx.request.query
  const result = await BuildingController.delBuilding(id)
  ctx.body = new ResBody({ data: result })
})

router.get("/getAdminTableData", async ctx => {
  const { buildingId } = ctx.request.query
  utils.checkParams({ buildingId })
  const building = await Building.findOne({ where: { id: buildingId } })
  const admins = await building.getAdmins()
  ctx.body = new ResBody({ data: { admins, total: admins.length } })
})

router.get("/getCleanerTableData", async ctx => {
  const { buildingId } = ctx.request.query
  utils.checkParams({ buildingId })
  const building = await Building.findOne({ where: { id: buildingId } })
  const cleaners = await building.getCleaners()
  ctx.body = new ResBody({ data: { cleaners, total: cleaners.length } })
})

router.post("/addAdminToBuilding", async ctx => {
  const { adminAccount, buildingId } = ctx.request.body
  const admin = await User.findOne({
    where: { account: adminAccount, role: "admin" }
  })
  if (!admin) {
    throw new Error("找不到该用户")
  }
  const result = await Building.addAdmin(buildingId, admin.id)
  if (!result) {
    throw new Error("403-目标管理员已为当前宿舍楼的管理员，添加失败")
  }
  ctx.body = new ResBody({ data: { result } })
})

router.del("/removeBuildingAdmin", async ctx => {
  const { adminId, buildingId } = ctx.request.query
  utils.checkParams({ adminId, buildingId })
  const building = await Building.findOne({ where: { id: buildingId } })
  const admin = await User.findOne({ where: { id: adminId } })
  const result = await building.removeAdmin(admin)
  ctx.body = new ResBody({ data: { effectRow: result } })
})

module.exports = router.routes()
